import 'dart:async';

import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_form_core/theme/base_form_theme.dart';
import 'package:x3_component_core/x3_component_core.dart';
import 'package:x3_form_core/controller/base_search_bar_controller.dart';

class BaseSearchComponent extends StatefulWidget {
  /// 初始值
  final String value;

  /// 提示文本
  final String hintText;

  final EdgeInsetsGeometry contentPadding;

  /// 把该输入框的焦点暴露出去
  final void Function(FocusNode focusNode) emitFocusNode;

  /// 输入框的控制器 可以不传 不传自己构造一个
  final TextEditingController controller;

  /// 清除值事件
  final VoidCallback onClearOut;

  /// 编辑完成的事件
  final ValueChanged<String> onEditingComplete;

  /// 是否默认获取焦点
  final bool autoFocus;

  /// 颜色
  final Color fillColor;

  /// 拓展栏
  final Widget expansion;

  /// 配置控制器 会覆盖原来的  hintText , expansion 值
  final BaseSearchBarController baseSearchBarController;

  /// 是否显示搜索按钮
  final bool showsSearchIcon;

  /// 输入内容显示的最大行数
  final int maxLines;

  const BaseSearchComponent({
    Key key,
    this.value,
    this.hintText = '请输入关键字',
    this.showsSearchIcon = true,
    this.onClearOut,
    this.controller,
    this.onEditingComplete,
    this.emitFocusNode,
    this.autoFocus = false,
    this.fillColor,
    this.expansion,
    this.baseSearchBarController,
    this.contentPadding,
    this.maxLines,
  }) : super(key: key);

  @override
  _BaseSearchComponentState createState() => _BaseSearchComponentState();
}

class _BaseSearchComponentState extends State<BaseSearchComponent> with AutomaticKeepAliveClientMixin, PdaListenerMixin<BaseSearchComponent> {
  /// 扩展行
  Widget expansion;

  /// 提示文本
  String hintText;

  /// 流
  StreamSubscription _streamSubscription;

  /// 隐藏搜索栏
  bool hideSearchBar = false;

  /// 默认的控制器 因为构造函数不能使用new的对象作为默认值
  TextEditingController _controller;

  /// 获取当前的控制器 参考TextField的源码
  TextEditingController get _effectiveController => widget.controller ?? _controller;

  @override
  void initState() {
    /// 扩展行
    expansion = widget.expansion;

    if (widget.controller == null) {
      _controller = TextEditingController();
    }

    /// 提示文本
    hintText = widget.hintText;

    /// 控制器事件
    if (widget.baseSearchBarController != null) {
      /// 监听流
      bool isStreamListener = widget.baseSearchBarController.streamController.hasListener;
      if (isStreamListener == false) {
        _streamSubscription = widget.baseSearchBarController.streamController.stream.listen((BaseSearchBarConfigModel _config) {
          /// 监听是否修改
          if (_config.expansion != null) expansion = _config.expansion;
          if (_config.hitText != null) hintText = _config.hitText;
          if (_config.hideSearchBar != null) hideSearchBar = _config.hideSearchBar;
          setState(() {});
        });
      }
    }
    super.initState();
  }

  @override
  void dispose() {
    _streamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ConstrainedBox(
      constraints: BoxConstraints(maxHeight: 40.0, minHeight: 40.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: Opacity(
              opacity: hideSearchBar == false ? 1 : 0,
              child: _buildSearchBar(),
            ),
          ),
          this.expansion == null ? SizedBox() : Container(margin: EdgeInsets.only(left: 6), child: this.expansion),
        ],
      ),
    );
  }

  Widget _buildSearchBar() {
    return BaseTextField(
      value: widget.value,
      fillColor: widget.fillColor,
      prefix: _buildPrefixIcon(),
      controller: _effectiveController,
      hintText: this.hintText,
      keyboardType: TextInputType.text,
      textInputAction: TextInputAction.search,
      autoFocus: widget.autoFocus,
      emitFocusNode: widget.emitFocusNode,
      onClearOut: _onClearOut,
      onSubmitted: _onSubmitted,
      contentPadding: widget.contentPadding,
      maxLines: widget.maxLines,
    );
  }

  /// 提交事件
  void _onSubmitted(String v) {
    /// 提交事件
    if (widget.onEditingComplete != null) widget.onEditingComplete(v);

    /// 控制器发布
    _onChangeSearchKey(v);
  }

  /// 清除值 事件
  void _onClearOut() {
    /// 提交事件
    if (widget.onClearOut != null) widget.onClearOut();

    /// 控制器发布
    _onChangeSearchKey('');
  }

  /// 改变 searchKey事件
  void _onChangeSearchKey(String v) {
    if (widget.baseSearchBarController != null) {
      widget.baseSearchBarController.changeSearchKey(v);
    }
  }

  /// 搜索小图标
  Widget _buildPrefixIcon() {
    return widget.showsSearchIcon == true
        ? Padding(
            padding: const EdgeInsets.only(left: 8.0, right: 2.0),
            child: Icon(BaseIconData.x3Search, size: 18, color: BaseFormTheme.hintColor),
          )
        : null;
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void onError(Object error) {
    _effectiveController.text = error.toString().trim();
  }

  @override
  void onEvent(Object code) {
    String text = code.toString().trim();
    _effectiveController.text = text;
    _onSubmitted(text);
    setState(() {});
  }
}
